package com.cskaoyan.order.mq.delay;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * DelayOrderCancelProducer
 *
 * @param
 * @return
 * @2022/4/26
 **/
@Component
@Slf4j
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    //    from package org.apache.rocketmq.client.producer;
//    annotation can not be used!
    @PostConstruct
//    after constructor !
    public void init() {
//        log.info("producer init! producer={}",producer.getCreateTopicKey());
        producer = new DefaultMQProducer("delay_order_cancel_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {

            producer.start();
            log.info("producer init! producer start");

        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
//该方法用来实现订单超时自动取消的延迟消息

    public boolean sendDelayOrderMessage(String orderId) {
        log.info("sendDelayOrderMessage! orderId={}",orderId);

//        send delay message! (when out of time limit)
        Message msg = new Message("delay_order_cancel", orderId.getBytes(Charset.forName("utf-8")));
        msg.setDelayTimeLevel(3);//10s
//        msg.setDelayTimeLevel(16);
        SendResult result=null;
        try {
            log.info("before producer.send(msg)!");
            result = producer.send(msg);
        } catch (MQClientException e) {
            log.info("Exception! e=",e.getErrorMessage());
            e.printStackTrace();
        } catch (InterruptedException e) {
            log.info("Exception! e=",e.getMessage());
            e.printStackTrace();
        } catch (RemotingException e) {
            log.info("Exception! e=",e.getMessage());
            e.printStackTrace();
        } catch (MQBrokerException e) {
            log.info("Exception! e=",e.getErrorMessage());
            e.printStackTrace();
        }
        log.info("send delay msg complete! result={}",result);
        if (result != null && SendStatus.SEND_OK.equals(result.getSendStatus())) {
            log.info("result.getSendStatus()={}",result.getSendStatus());

            return true;
        }
        log.info("result.getSendStatus()={}",result.getSendStatus());

        return false;
    }
}
